#通用方法
#匹配图片
import aircv as ac
#读取图片
import cv2
import numpy as np
import os
#时间
import time
import random
import sys
#日志
import logging
import shutil
from PIL import Image

def log(message,filename):
    logging.basicConfig(
                level    = logging.DEBUG,
                format   = '%(asctime)s\tFile \"%(filename)s\",line %(lineno)s\t%(levelname)s: %(message)s',
                # datefmt  = '%a, %d %b %Y %H:%M:%S',
                filename = "./log/" + filename + ".log",
                filemode = 'w')
    #添加StreamHandler在控制台也打印出来
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter = logging.Formatter('LINE %(lineno)-4d : %(levelname)-8s %(message)s')
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)
    logging.info(message)
def getExtPhone(phone):
    if phone:
        return  '-s %s:5555 '%phone
    else:
        return ''
#home
def home(phone=''):
    mobile = getExtPhone(phone)
    os.system('adb %s shell  input keyevent 3'%mobile)
def back(phone=''):
    mobile = getExtPhone(phone)
    os.system('adb  %s shell input keyevent 4'%mobile)
#发送屏幕点击
def tap_screen(x,y,phone=''):
    mobile = getExtPhone(phone)
    os.system('adb {} shell input tap {} {}'.format(mobile,x,y))
#发送屏幕滑动  xy 初始坐标 x1y1目标坐标 t 持续时间 ms
def swipe_screen(x,y,x1,y1,t=1000,phone=''):
    mobile = getExtPhone(phone)
    os.system('adb {} shell input swipe {} {} {} {} {}'.format(mobile,x,y,x1,y1,t))
#摇杆方向上
def up_bar(phone=''):
    t = random.randint(1000,5000)
    print (t)
    swipe_screen(244,845,175,715,t)
#摇杆方向下
def down_bar():
    t = random.randint(1000,5000)
    print (t)
    swipe_screen(244,845,308,940,t)
#摇杆方向左
def left_bar():
    t = random.randint(1000,5000)
    print (t)
    swipe_screen(244,845,55,998,t)
#摇杆方向右
def right_bar():
    t = random.randint(1000,5000)
    print (t)
    swipe_screen(244,845,386,696,t)

#截取屏幕
def screenShot(shotPath,shotName='tmp'):
    # shotName = "%s.jpg" % shotName
    # shotFullPath = os.path.join(shotPath,shotName)
    # srcfile = r"G:\python\img\tmp1.jpg"
    # shutil.copyfile(srcfile, shotFullPath)
    # return shotFullPath
    #清理缓存图片
    shotName = "%s.jpg"%shotName
    shotFullPath = os.path.join(shotPath,shotName)
    if os.path.isfile(shotFullPath):
        try:
            os.remove(shotFullPath)
            print("清理图片%s"%(shotFullPath))
        except IOError:
            print("清理图片失败%s"%(shotFullPath))
            pass
    #截图命令
    shotCommnet = "adb shell screencap -p /sdcard/%s"%(shotName)
    #拉取命令
    pullComment = "adb pull /sdcard/%s %s"%(shotName,shotPath)
    b = os.system(shotCommnet)#截图文件保存在脚本的目录下
    a = os.system(pullComment)
    if a==b==0:
        return shotFullPath
    else:
        return False

#匹配图片
def matchImg(imgsrc,imgobj,confidencevalue=0.8):#imgsrc=原始图像，imgobj=待查找的图片
    #print(imgobj)
    #exit()
    imsrc = ac.imread(imgsrc)
    imobj = ac.imread(imgobj)
    match_result = ac.find_template(imsrc,imobj,confidencevalue)  # {'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)}
    if match_result is not None:
        match_result['shape']=(imsrc.shape[1],imsrc.shape[0])#0为高，1为宽
    return match_result
 #匹配多张
def matchImgs(imgsrc,imgobj,confidencevalue=0.8):
        #print(imgsrc)
    #exit()
    imsrc = ac.imread(imgsrc)
    #imsrc = cv2.imread(imgsrc,0)
    imobj = ac.imread(imgobj)
    #imobj = cv2.imread(imgobj,0)
    match_result = ac.find_all_template(imsrc,imobj,confidencevalue)  # {'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)}
    return match_result
#读取图片 中文路径
def cv_imread(file_path):
    cv_img = cv2.imdecode(np.fromfile(file_path,dtype=np.uint8),-1)
    return cv_img
#转换为灰度图
def imgGray(t1):
    img = Image.open(t1)
    Img = img.convert('L')
    Img.save(t1)
def click_draw(imgPath,pos):
    #格式化坐标
    pos = formatPos(pos)
    img = cv2.imread(imgPath)
    # 画一个填充红色的圆，参数2：圆心坐标，参数3：半径
    cv2.circle(img,pos, 63, (0, 0, 255), 8)
    #cv2.namedWindow("Image",cv2.WINDOW_NORMAL) #创建窗口并且设置为自动调整窗口
    #cv2.imshow('Image', img)  #显示图像,窗口会自动调整图像大小.第一个参数是窗口的名字,第二个才是我们的图像 && 名字必须不同
    cv2.imwrite(imgPath,img)
    #cv2.waitKey (0)#0无限等待键盘输入
    #exit()
    #cv2.waitKey (0)#0无限等待键盘输入
#格式化浮点坐标为int坐标
def formatPos(pos):
    if 'result' in pos:
        posx = int(pos['result'][0])
        posy = int(pos['result'][1])
    else:
        x,y = pos
        posx = int(x)
        posy = int(y)
    res = (posx,posy)
    return res

def drawImg(t1,center,radius=63,color=(0, 0, 255),thickness=8):
    img = cv2.imread(t1)
    # 画一个填充红色的圆，参数2：圆心坐标，参数3：半径 4颜色 5 正为粗细 负数为实心
    cv2.circle(img,center, radius, color, thickness)
    cv2.namedWindow("Image",cv2.WINDOW_NORMAL) #创建窗口并且设置为自动调整窗口
    cv2.imshow('Image', img)  #显示图像,窗口会自动调整图像大小.第一个参数是窗口的名字,第二个才是我们的图像 && 名字必须不同
    cv2.waitKey (0)#0无限等待键盘输入
#启动队列
def startQueue():
    return queue.Queue()
#放入队列
def putQueue(queue,content):
    queue.put(content)
#格式化消息
def formatMsg(msg,code=1):
    content = {'msg':msg,'code':code}
    return content
#格式化图片
def formatStage(path):
    content = {'stage':path}
    return content
#格式化图片
def formatAction(path):
    content = {'action':path}
    return content
def getPhoneType():
    #获取手机名称
    deviceName = os.popen('adb shell getprop ro.product.model').read()
    #print(deviceName)
    #获取手机版本
    #platformVersion = os.popen('adb shell getprop ro.build.version.release').read()
    #print(platformVersion)
    #获取手机厂商
    #device = os.popen('adb shell getprop ro.product.name ').read()
#获取手机ip并连接
def conectPhone():
    os.system('adb disconnect')
    commond = 'adb shell "ip addr | grep global| grep -E -o '"'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'"'"'
    out = os.popen(commond).read()
    ip = out.split()
    if ip:
        print (ip)
        return  ip[0]
    else:
        print ('找不到设备')
    # if ip:
    #     os.system('adb connect %s'%ip[0])
    #     print('设备连接成功')
    #     return ip[0]
    # else:
    #     print('找不到无线设备')
    #     exit()
#亮屏操作
def wakePhone():
    commond = 'adb shell "dumpsys window policy|grep '"mAwake"'"'
    out = os.popen(commond).read()
    str = out.split('=')
    if (str[1] == 'false\n'):
        return 1
    return 0
#是否锁屏
def isLock():
    commond = 'adb shell "dumpsys window policy|grep '"mIsShowing"'"'
    out = os.popen(commond).read()
    str = out.split('=')
    if (str[1] == 'true\n'):
        return 1
    return 0
#执行带返回的命令
def osCommand(com):
    out = os.popen(com).read()
    return out
